package com.color.admin.common.core.utils.web;


import com.color.admin.common.core.base.AuthInterceptor;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/**
 * @author HaiQiu
 * @date 2021/11/19
 * servlet常用工具
 */
public class ServletUtils {

    /**
     * 获取request
     * @return request
     */
    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
    }

    /**
     * 获取response
     * @return response
     */
    public static HttpServletResponse getResponse(){
        return ((ServletRequestAttributes) Objects.requireNonNull (RequestContextHolder.getRequestAttributes())).getResponse();
    }

    /**
     * 获取用户名
     * @return 用户名
     */
    public static String getUsername(){
        String username = (String) getRequest().getAttribute(AuthInterceptor.USER_NAME);
        return username;
    }

    /**
     * 获取用户ID
     * @return ID
     */
    public static String getUserId(){
        String userId = (String) getRequest().getAttribute(AuthInterceptor.USER_ID);
        return userId;
    }
}
